<template>
  <el-cascader :style="{
    width: proxy.$size(width, '100%'),
  }" v-model="keyword" v-bind="{
    placeholder: '请选择',
    clearable: true,
    ...$attrs,
    filterable: true,
    disabled: typeof $attrs.disabled === 'function' ? $attrs.disabled(data) : $attrs.disabled
  }" :props="{
    label: labelName,
    value: valueName,
    children: childrenName,
  }" :options="options" @change="changeBtn">
  </el-cascader>
</template>
<script setup lang="ts">
import { getCurrentInstance, reactive, onMounted, ref } from 'vue';
const { proxy } = getCurrentInstance() as any;
//获取父级数据
const props = withDefaults(
  defineProps<{
    data: any;
    dataName?: any;
    width?: number | string; //宽度
    options?: any; //
    labelName?: string; //
    valueName?: string; //
    childrenName?: string; //
  }>(),
  {
    type: '',
    size: 'default',
    clearable: true,
    filterable: true,
    placeholder: '请选择',
    labelName: 'label',
    valueName: 'value',
    childrenName: 'children',
  },
);
const r_data = reactive({
  loading: false,
  options: [],
});
const keyword = computed({
  get() {
    if (props.dataName) {
      return serData.value.map((key: string) => props.data[key]);
    } else {
      return props.data || [];
    }
  },
  set(val) {
    serData.value.forEach((key: any, index: number) => {
      props.data[key] = val ? val[index] : '';
    });
  },
});
const serData = computed(() => {
  let _arr = [];
  if (props.dataName) {
    if (Array.isArray(props.dataName)) {
      _arr = props.dataName;
    }
  }
  return _arr;
});

const emit = defineEmits<{
  //fn为父组件引入子组件是定义的子组件事件属性，可随意定义
  (event: 'changeBtn', val: any, item: any): void;
}>();
const changeBtn = (value: any) => {
  emit('changeBtn', value, props.data);
};
//远程搜索
const get_options = () => {
  if (props.optionsName) {
    r_data.loading = true;
    const api: any = {
      GetTreeAreaDataList: {
        label: '地区',
        get: () => {
          isOptions();

        },
      },
    };
    if (api[props.optionsName]) {
      api[props.optionsName].get();
    } else {
      for (const key in api) {
        if (api[key].label === props.optionsName) {
          api[key].get();
        }
      }
    }
  }
  function isOptions() {
    if (r_data.options.length > 0) {
      r_data.loading = false;
      return;
    }
  }
};
onMounted(() => {
  r_data.options = props.options ? r_data.options.concat(props.options) : [];
  get_options();
});
</script>
<style scoped></style>
